//
//  HMCollectionViewController.m
//  HMMeituanHD
//
//  Created by apple on 2017/5/22.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMCollectionViewController.h"
#import "HMDetailViewController.h"

#import "HMDealModel.h"

#import "HMDealCell.h"

@interface HMCollectionViewController ()<DPRequestDelegate,UICollectionViewDelegate>

//无团购图片视图
@property (nonatomic, strong) UIImageView *nodealImageV;

@end

@implementation HMCollectionViewController

static NSString * const reuseIdentifier = @"dealCell";

- (instancetype)init
{
    //设置布局
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    //设置Item的尺寸
    layout.itemSize = CGSizeMake(HMDealCellWidth, HMDealCellWidth);
    
    self = [super initWithCollectionViewLayout:layout];
    if (self) {
        
        //设置背景色
        self.collectionView.backgroundColor = HMColor(228, 228, 228);
        //注册Cell 取出从xib中描述的cell
        [self.collectionView registerNib:[UINib nibWithNibName:@"HMDealCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Register cell classes
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

    //监听设备朝向 特点: 应用启动时,会自动调用一次响应方法,无论朝向是否改变
    [HMNoteCenter addObserver:self selector:@selector(baseOrientationDidChangeNote) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    
    //初始化刷新控件
    [self setupRefresh];
    
    //主动调用朝向通知的响应方法
    [self baseOrientationDidChangeNote];
    
}

#pragma mark - 刷新处理

//初始化刷新控件
- (void)setupRefresh{
    
    //解除循环引用
    __weak typeof(self) weakSelf = self;
    
    //一旦执行一个刷新操作,就应该禁用另一个刷新操作,直到正在执行的刷新操作返回结果
    
    //设置下拉刷新控件
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{  //下拉刷新执行的操作
        
        //禁用(隐藏)上拉加载
        weakSelf.collectionView.mj_footer.hidden = YES;
        
        //下拉刷新
        [self loadNewData];
    }];
    
    //设置上拉加载更多
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{ //上拉加载更多执行的操作
        //禁用下拉刷新
        self.collectionView.mj_header.hidden = YES;
        //上拉加载
        [self loadMoreData];
    }];
    //默认隐藏上拉加载
    self.collectionView.mj_footer.hidden = YES;
    
    
    
    //设置下拉刷新完成处理
    [self.collectionView.mj_header setEndRefreshingCompletionBlock:^(){
        
        //根据是否有数据,显隐上拉加载
        weakSelf.collectionView.mj_footer.hidden = (weakSelf.deals.count) ? NO : YES;
    }];
    
    //设置上拉加载完成处理
    [self.collectionView.mj_footer setEndRefreshingCompletionBlock:^(){
        
        //上拉完成,显示下拉刷新控件
        weakSelf.collectionView.mj_header.hidden = NO;
    }];
}

/**
 * 刷新逻辑:
 下拉刷新: 请求page = 1
 上拉加载更新: 请求page++
 */

//下拉刷新
- (void)loadNewData{
    
    _currentPage = 1;
    
    //请求数据
    [self requestDataFromDPAPI];
}

//上拉加载更新
- (void)loadMoreData{
    
    _currentPage++;
    //请求数据
    [self requestDataFromDPAPI];
}


#pragma mark - 网络请求

- (void)requestDataFromDPAPI{
    //设置参数
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    //设置城市 必须设置
    [param setValue:self.currentCityName forKey:@"city"];
    //设置页码
    [param setValue:@(self.currentPage) forKey:@"page"];
    //设置限定
    [param setValue:@3 forKey:@"limit"];
    
    //设置自定义参数
    if ([self respondsToSelector:@selector(addCustemParam:)]) {
        
        HMRequestType type = [(id<HMRequestParam>)self addCustemParam:param];
        //根据不同请求类型做处理
        switch (type) {
            case HMRequestTypeNetwork:
            {
            
                //请求团购数据
                [[DPAPI new] requestWithURL:@"v1/deal/find_deals" params:param delegate:self];
            }
                break;
            case HMRequestTypeClearUI:
            {
            
                //清空数据源
                self.deals = nil;
                //刷新界面
                [self.collectionView reloadData];
                //停止刷新控件
                [self.collectionView.mj_header endRefreshing];
                [self.collectionView.mj_footer endRefreshing];
            }
                
            default:
                break;
        }
        
    } else {
    
        //请求团购数据
        [[DPAPI new] requestWithURL:@"v1/deal/find_deals" params:param delegate:self];
    }

}



//获取数据成功
- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result{
    
    //判断上拉加载更多/下拉刷新 根据页码区分
    if (self.currentPage == 1) { //下拉刷新
        
        //清空数据源数组
        self.deals = nil;
    }
    
    NSArray *dictArr = result[@"deals"];
    //字典转模型
    //上拉加载更多 要求累加数据  使用可变数组来进行操作
    [self.deals addObjectsFromArray:[NSArray yy_modelArrayWithClass:[HMDealModel class] json:dictArr]];
    //刷新界面
    [self.collectionView reloadData];
    
    
    //停止刷新控件
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
    
    //根据是否有数据,显隐无数据图片  需要根据总数据进行判断,不要使用当前请求获取的数量
    self.nodealImageV.hidden = (self.deals.count) ? YES : NO;
}


//获取数据失败
- (void)request:(DPRequest *)request didFailWithError:(NSError *)error{
    
    HMLog(@"获取数据失败%@", error);
    //上拉加载失败后,让当前页码回滚
    _currentPage--;
    //停止刷新控件
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}


#pragma mark - 通知相关

//设备朝向变化调用
- (void)baseOrientationDidChangeNote{
    
    //列数
    NSInteger columnCount = UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation) ? 2 : 3;
    
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
    HMLog(@"%f, %f", [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    //iOS系统在横竖屏切换后,不会立即更新视图(window/view/screen)宽高属性
    //获取屏幕真实宽度的办法: 判断横竖屏,横屏取宽高较大值,竖屏宽高较小值
    //计算间距  屏幕宽度 = item宽度 * 列数 + 间距 * (列数 + 1)
    CGFloat margin = (HMRealScreenWidth - HMDealCellWidth * columnCount) / (columnCount + 1);
    
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *) self.collectionViewLayout;
    
    //设置组边距(外边距)
    layout.sectionInset = UIEdgeInsetsMake(margin, margin, margin, margin);
    //设置行间距
    layout.minimumLineSpacing = margin;
    //    });
    
}


#pragma mark <UICollectionViewDataSource>


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.deals.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HMDealCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    // 传递模型
    cell.dealModel = self.deals[indexPath.row];
    
    return cell;
}


#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HMDetailViewController *detailVc = [HMDetailViewController new];
    //传递数据模型
    detailVc.dealModel = self.deals[indexPath.row];
    [self presentViewController:detailVc animated:YES completion:nil];
}

#pragma mark - 懒加载

- (NSString *)currentCityName{
    
    if (_currentCityName == nil) {
        _currentCityName = @"北京";
    }
    return _currentCityName;
}


- (NSMutableArray<HMDealModel *> *)deals{
    if (_deals == nil) {
        _deals = [NSMutableArray array];
    }
    return _deals;
}

- (UIImageView *)nodealImageV{
    if (_nodealImageV == nil) {
        _nodealImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_deals_empty"]];
        //添加到视图中
        [self.view addSubview:_nodealImageV];
        //设置位置
        [_nodealImageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.collectionView);
        }];
        //设置填充模式
        _nodealImageV.contentMode = UIViewContentModeCenter;
    }
    return _nodealImageV;
}

@end
